﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.JsonSerialization;
using Furion.RemoteRequest.Extensions;
using iemtm.WeChat.Core.Extension.Helper;
using iemtm.WeChat.Core.Managers;
using iemtm.WeChat.Core.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.Util
{
    public static class WeiXinPush
    {
        /// <summary>
        /// 工单审核失败推送
        /// </summary>
        /// <param name="UserCode"></param>
        /// <param name="AnnounceCode"></param>
        /// <param name="JobNumber"></param>
        /// <param name="AuditRemark"></param>
        /// <returns></returns>
        public static async Task<WxResultModel> SendUnAnnounce(string UserCode, string AnnounceCode, string JobNumber, string AuditRemark)
        {
            

                WxResultModel result = new WxResultModel() { errcode = 40003 };
                //查询用户信息
                UserAccount userinfo = new UserAccount() { UserCode = UserCode };
                userinfo =await App.GetService<IUserManager>().CheckUserAsync(UserCode);
                //EntityQuery<UserAccount>.QueryObject(OQL.From(userinfo).Select().Where(userinfo.UserCode).END);

                if (userinfo != null && !string.IsNullOrEmpty(userinfo.WxOpenId))
                {
                    try
                    {
                        var parJson = new
                        {
                            touser = userinfo.WxOpenId,
                            template_id = WeChatHelper.WeiXinConfig.audit_template_id,
                            url = $"{WeChatHelper.WeiXinConfig.domain}/AnnouceList/Detail?annouceCode={AnnounceCode}",
                            topcolor = "#FF0000",
                            data = new
                            {
                                first = new WxTemplateDataModel() { value = $"收到一条工单审核不通过信息，请及时查看\r\n", color = "#FF0000" },
                                keyword1 = new WxTemplateDataModel() { value = $"{JobNumber}\r\n", color = "#0000FF" },
                                keyword2 = new WxTemplateDataModel() { value = $"动环工单号:{JobNumber} 审核不通过\r\n审核备注:{AuditRemark}\r\n", color = "#0000FF" },
                                remark = new WxTemplateDataModel() { value = "请及时核查并处理\r\n", color = "#808080" }
                            }
                        };
                        result = PushApi(parJson);
                    }
                    catch (Exception ex)
                    {
                        Log log = new Log() { LogName = "工单审核失败推送失败", LogDetails = ex.ToString(), CreateTime = DateTime.Now };
                        var entityRepository =await Db.GetRepository<Log>().InsertAsync(log);
                    }
                }
                return result;
           
        }


        /// <summary>
        /// 告警提醒(红色字体)
        /// </summary>
        ///  退服告警服务提醒
        ///  { { first.DATA} }
        ///  已派单: { { ky1.DATA} }
        ///  停电: { { ky2.DATA} }
        ///  正在发电: { { ky3.DATA} }
        ///  可用油机: { { ky4.DATA} }
        ///  { { remark.DATA} }
        /// <param name="userCode"></param>
        /// <param name="dataModel"></param>
        public static WxResultModel SendAlarmTemplateMsg(string userCode, AlarmCountModel dataModel)
        {
            WxResultModel result = new WxResultModel() { errcode = 40003 };


            var userinfo = Db.GetRepository<UserAccount>().FirstOrDefault(u=>u.UserCode == userCode ); 
            if (userinfo != null && !string.IsNullOrEmpty(userinfo.WxOpenId))
            {
                try
                {
                    var parJson = new
                    {
                        touser = userinfo.WxOpenId,
                        template_id = WeChatHelper.WeiXinConfig.alarmMsg_template_id,
                        //url = $"{WxConfig.Config.domain}/Alarm/Index",
                        url = $"{WeChatHelper.WeiXinConfig.domain}/Home/Menu",
                        topcolor = "#FF0000",
                 
                        data = new
                        {
                            //first = new WxTemplateDataModel { value = $"当前共有{dataModel.OutServiceAmount}条基站退服告警[移动{dataModel.OutServiceAmountByYD},联通{dataModel.OutServiceAmountByLT},电信{dataModel.OutServiceAmountByDX}],请您及时做好保障措施.", color = "#FF0000" },
                            first = new WxTemplateDataModel { value = $"贵州铁塔运维管理服务号为您推送告警信息.", color = "#FF0000" },
                            content = new WxTemplateDataModel() { value = $"告警提醒\r\n退服告警: {dataModel.OutServiceAmount}个 [移动{dataModel.OutServiceAmountByYD},联通{dataModel.OutServiceAmountByLT},电信{dataModel.OutServiceAmountByDX}] \r\n停电告警:{dataModel.MainsFailAmount}个 [移动{dataModel.MainsFailAmountByYD},联通{dataModel.MainsFailAmountByLT},电信{dataModel.MainsFailAmountByDX}] \r\n离线告警:{dataModel.FSUAmount}个 [移动{dataModel.FSUAmountByYD},联通{dataModel.FSUAmountByLT},电信{dataModel.FSUAmountByDX}] \r\n今日发电工单: 已派{dataModel.TodayAnnouce}张,发电中{dataModel.TodayInAnnouce}张 \r\n本周发电工单: 已派{dataModel.WeekAnnouce}张,已发电{dataModel.WeekOldAnnouce}张 \r\n可用油机: {dataModel.IdleAmount}台\r\n", color = "#0000FF" },
                            occurtime = new WxTemplateDataModel() { value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), color = "#0000FF" },
                            remark = new WxTemplateDataModel() { value = "\r\n请及时做好保障措施", color = "#808080" }
                        }
                    };
                    result = PushApi(parJson);
                }
                catch (Exception e)
                {
                    Db.GetRepository<Log>().Insert(new Log() { LogName = "推送告警信息失败", LogDetails = e.ToString(), CreateTime = DateTime.Now });
                }
            }
            return result;
        }

        /// <summary>
        /// 推送指标通报
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static WxResultModel SendInformataionMsg(string userCode, AnnouceCountByWxPushModel model)
        {
            WxResultModel result = new WxResultModel() { errcode = 40003 };
            var userinfo = Db.GetRepository<UserAccount>().FirstOrDefault(u => u.UserCode == userCode);
            if (userinfo != null && !string.IsNullOrEmpty(userinfo.WxOpenId))
            {
                try
                {
                    var parJson = new
                    {
                        touser = userinfo.WxOpenId,
                        template_id = WeChatHelper.WeiXinConfig.indicators_template_id,
                        url = $"{WeChatHelper.WeiXinConfig.domain}/Information/Index",
                        topcolor = "#FF0000",
                        data = new
                        {
                            first = new WxTemplateDataModel { value = $"发电报表已更新，请注意查收\r\n", color = "#FF0000" },
                            keyword1 = new WxTemplateDataModel() { value = $"指标通报提醒\r\n日报：总工单{model.AllAnnouceCountByDaily}条，已完成{model.FiAnnnouceCountByDaily}条，未接单{model.noExtAnnouceCountByDaily}条\r\n周报：总工单{model.AllAnnouceCountByWeek}条，已完成{model.FiAnnnouceCountByWeek}条，未接单{model.noExtAnnouceCountByWeek}条\r\n月报：总工单{model.AllAnnouceCountByMon}条，已完成{model.FiAnnnouceCountByMon}条，未接单{model.noExtAnnouceCountByMon}条\r\n", color = "#0000FF" },
                            keyword2 = new WxTemplateDataModel() { value = DateTime.Now.ToString(), color = "#0000FF" },
                            remark = new WxTemplateDataModel() { value = "\r\n点击可查看信息内容", color = "#808080" }
                        }
                    };
                    result = PushApi(parJson);
                }
                catch (Exception e)
                {
                    Db.GetRepository<Log>().Insert(new Log() { LogName = "推送指标通报失败", LogDetails = e.ToString(), CreateTime = DateTime.Now });
                }
            }
            return result;
        }


        /// <summary>
        /// 铁塔审核工单推送
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="Count"></param>
        /// <returns></returns>
        public static WxResultModel SendAnnounceAuditMsg(string userCode, int? Count = 0)
        {
            WxResultModel result = new WxResultModel() { errcode = 40003 };
            var userinfo = Db.GetRepository<UserAccount>().FirstOrDefault(u => u.UserCode == userCode); 
            if (userinfo != null && !string.IsNullOrEmpty(userinfo.WxOpenId))
            {
                try
                {
                    var parJson = new
                    {
                        touser = userinfo.WxOpenId,
                        template_id = WeChatHelper.WeiXinConfig.indicators_template_id,
                        url = $"{WeChatHelper.WeiXinConfig.domain}/Home/Menu",
                        topcolor = "#FF0000",
                        data = new
                        {
                            first = new WxTemplateDataModel { value = $"有新的工单需要审核，请注意查收\r\n", color = "#FF0000" },
                            keyword1 = new WxTemplateDataModel() { value = $"工单审核提醒\r\n\r\n待审工单数量：{Count}条\r\n", color = "#0000FF" },
                            keyword2 = new WxTemplateDataModel() { value = DateTime.Now.ToString(), color = "#0000FF" },
                            remark = new WxTemplateDataModel() { value = "\r\n点击可查看信息内容", color = "#808080" }
                        }
                    };
                    result = PushApi(parJson);
                }
                catch (Exception e)
                {
                    Db.GetRepository<Log>().Insert(new Log() { LogName = "审核工单推送失败", LogDetails = e.ToString(), CreateTime = DateTime.Now });
                }
            }
            return result;
        }


        /// <summary>
        /// 油机保养提醒推送
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="GenNum"></param>
        /// <returns></returns>
        public static WxResultModel SendGenRunMsg(string userCode, string GenNum)
        {
            WxResultModel result = new WxResultModel() { errcode = 40003 };
            var userinfo = Db.GetRepository<UserAccount>().FirstOrDefault(u => u.UserCode == userCode);
            if (userinfo != null && !string.IsNullOrEmpty(userinfo.WxOpenId))
            {
                try
                {
                    var parJson = new
                    {
                        touser = userinfo.WxOpenId,
                        template_id = WeChatHelper.WeiXinConfig.indicators_template_id,
                        url = $"{ WeChatHelper.WeiXinConfig.domain}/Generator/Index",
                        topcolor = "#FF0000",
                        data = new
                        {
                            first = new WxTemplateDataModel { value = $"有维护保养计划需要执行\r\n", color = "#FF0000" },
                            keyword1 = new WxTemplateDataModel() { value = $"油机编号:'{GenNum}'已运行超过100小时\r\n", color = "#0000FF" },
                            keyword2 = new WxTemplateDataModel() { value = DateTime.Now.ToString(), color = "#0000FF" },
                            remark = new WxTemplateDataModel() { value = "\r\n请按时执行", color = "#808080" }
                        }
                    };
                    result = PushApi(parJson);
                }
                catch (Exception e)
                {
                    Db.GetRepository<Log>().Insert(new Log() { LogName = "油机保养提醒推送失败", LogDetails = e.ToString(), CreateTime = DateTime.Now });
                }
            }
            return result;
        }


        /// <summary>
        /// 推送接口
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static  WxResultModel PushApi(object obj)
        {
            //检查token是否过期
             string url= $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={WeChatHelper.WeiXinConfig.access_token}";
            string JsonData = JSON.GetJsonSerializer().Serialize(obj);
            string resultV =PostJsonPararmter(JsonData, url);
            WxResultModel returndata = JSON.GetJsonSerializer().Deserialize<WxResultModel>(resultV);
            return returndata;
            #region 参数 传不对

            //byte[] bytes = Encoding.UTF8.GetBytes(JsonData);
            //var response= await url.SetContentType("application/json").SetContentEncoding(Encoding.UTF8).SetBody(bytes).PostAsync();
            ////var response= await url.SetBody(bytes,"json", Encoding.UTF8).PostAsync();
            //string resultV = response.Content.ReadAsStringAsync().Result;
            //WxResultModel returndata = JSON.GetJsonSerializer().Deserialize<WxResultModel>(resultV);

            //return returndata;
            #endregion

        }
        /// <summary>
        /// PostJson参数
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string PostJsonPararmter(string jsonString, string url)
        {
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "POST";
                request.ContentLength = bytes.Length;
                request.ContentType = "json";
                Stream reqstream = request.GetRequestStream();
                reqstream.Write(bytes, 0, bytes.Length);
                //声明一个HttpWebRequest请求  
                request.Timeout = 1000 * 30;
                //设置连接超时时间  
                request.Headers.Set("Pragma", "no-cache");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream streamReceive = response.GetResponseStream();
                Encoding encoding = Encoding.UTF8;
                StreamReader streamReader = new StreamReader(streamReceive, encoding);
                string strResult = streamReader.ReadToEnd();
                streamReceive.Dispose();
                streamReader.Dispose();
                return strResult;
            }
            catch (Exception ex)
            {
                return "";
            }
        }



    }


    public class WxResultModel
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
    }
    public class WxTemplateDataModel
    {
        public string value { get; set; }
        public string color { get; set; }
    }
}
